package com.clothes.act;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.clothes.R;
import com.clothes.adp.Aadapter;
import com.clothes.app.BaseUrl;
import com.clothes.http.JsonCallBack;
import com.clothes.mdoel.ASearchInfo;
import com.clothes.mdoel.ClothesTable;
import com.clothes.mdoel.ServerInfo;
import com.clothes.utils.DateTool;
import com.clothes.views.CustomListView;
import com.clothes.views.pull.PullToRefreshLayout;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.GetRequest;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

public class ASearch extends BaseActivity {

    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.et_worker_num)
    EditText etWorkerNum;
    @Bind(R.id.tv_name)
    TextView mTvName;
    @Bind(R.id.tv_begin_time)
    TextView tvBeginTime;
    @Bind(R.id.tv_end_time)
    TextView tvEndTime;
    @Bind(R.id.lv_a)
    CustomListView lvA;
    @Bind(R.id.refresh_view)
    PullToRefreshLayout refreshView;

    private List<ClothesTable> list = new ArrayList<>();
    private List<ClothesTable> listAll = new ArrayList<>();
    private Aadapter adapter;

    @Override
    public void initView() {
        setContentView(R.layout.activity_asearch);
    }

    @Override
    public void initData() {
        mImmersionBar.statusBarColor(R.color.colorPrimaryDark).init();
        tvTitle.setText("领货交货明细");
        tvBeginTime.setText("2018-01-01");
        tvEndTime.setText(DateTool.getStringDate(System.currentTimeMillis(),"yyyy-MM-dd"));
        setTime(3);
        adapter = new Aadapter(this,listAll);
        lvA.setAdapter(adapter);

        //禁止上拉 下拉刷新
        refreshView.setPullDownEnable(false);
        refreshView.setPullUpEnable(false);
        refreshView.setOnPullListener(new PullToRefreshLayout.OnPullListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                // 下拉刷新操作
                refresh();
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                // 下拉刷新操作
                loadMore();
            }
        });
        etWorkerNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String txt = charSequence.toString().trim();
                if(txt.length() > 1){
                    refreshView.setPullDownEnable(true);
                    //TODO 请求姓名
                    getName(txt);
                }else {
                    mTvName.setVisibility(View.GONE);
                    refreshView.setPullDownEnable(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    //刷新
    private void refresh(){
        pageNum = 0;
        refreshView.setPullUpEnable(true);
        getHttp();
    }
    //加载
    private void loadMore(){
        pageNum++;
        getHttp();
    }

    //请求网络
    private void getHttp(){
        String num = etWorkerNum.getText().toString();
        GetRequest<ServerInfo<ASearchInfo>> request = OkGo.get(BaseUrl.ASerch2);
        if(!num.equals(""))
        request.params("workerNum",num);
        request.params("pageIndex",pageNum)
                .params("pageSize",pageSize)
                .params("beginClaimedDate",tvBeginTime.getText().toString())
                .params("endClaimedDate",tvEndTime.getText().toString()+" 23:59")
                .execute(new JsonCallBack<ServerInfo<ASearchInfo>>() {
                    @Override
                    public void onSuccess(Response<ServerInfo<ASearchInfo>> response) {
                        if(pageNum == 0) {
                            refreshView.refreshFinish(PullToRefreshLayout.SUCCEED);
                            listAll.clear();
                        }else {
                            refreshView.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                        }
                        ServerInfo serverInfo = response.body();
                        ASearchInfo info = (ASearchInfo) serverInfo.getData();
                        list =  info.getResults();
                        if(list.size() < 20){
                            if(pageNum > 0){
                                showToast("数据已经全部加载");
                            }
                            refreshView.setPullUpEnable(false);
                        }else {
                            refreshView.setPullUpEnable(true);
                        }

                        listAll.addAll(list);
                        adapter.setList(listAll);
                    }

                    @Override
                    public void onError(Response<ServerInfo<ASearchInfo>> response) {
                        if(pageNum == 0)
                            refreshView.refreshFinish(PullToRefreshLayout.SUCCEED);
                        else
                            refreshView.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                        showToast("服务器请求失败");
                    }
                });
    }

    @OnClick({R.id.iv_back, R.id.tv_begin_time, R.id.tv_end_time, R.id.iv_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.tv_begin_time:
                t = 1;
                timePickerView.show();
                break;
            case R.id.tv_end_time:
                t= 2;
                timePickerView.show();
                break;
            case R.id.iv_search:
                getHttp();
                break;
        }
    }

    private int t;
    @Override
    protected void setTimeText(String time) {
        if(t == 1)
            tvBeginTime.setText(time);
        else
            tvEndTime.setText(time);
    }

    //根据工号请求姓名
    private void getName(String wokerNum){
        OkGo.<String>get(BaseUrl.GetName)
                .params("emplno",wokerNum)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String res = response.body().toString();
                        try {
                            JSONObject object = new JSONObject(res);
                            if(object.has("data")){
                                JSONArray array = object.getJSONArray("data");
                                if(array.length()>0){
                                    JSONObject obj = array.getJSONObject(0);
                                    String name = obj.getString("realName");
                                    mTvName.setVisibility(View.VISIBLE);
                                    mTvName.setText(name);
                                }else {
                                    mTvName.setVisibility(View.GONE);
                                }
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        mTvName.setVisibility(View.GONE);
                    }
                });
    }
}
